﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Management;

namespace YY.Admin.Core.Util
{
    public static class DeviceInfoUtil
    {
        public static async Task<string> GetPublicIpAddressAsync()
        {
            try
            {
                using (var client = new System.Net.Http.HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(3);
                    var response = await client.GetStringAsync("https://api.ipify.org");
                    return response.Trim();
                }
            }
            catch
            {
                // 备用方案
                try
                {
                    using (var client = new System.Net.Http.HttpClient())
                    {
                        client.Timeout = TimeSpan.FromSeconds(3);
                        var response = await client.GetStringAsync("https://ipinfo.io/ip");
                        return response.Trim();
                    }
                }
                catch
                {
                    return "无法获取公网IP";
                }
            }
        }

        public static IEnumerable<string> GetLocalIpAddresses()
        {
            try
            {
                var host = Dns.GetHostEntry(Dns.GetHostName());
                return host.AddressList
                    .Where(ip => ip.AddressFamily == AddressFamily.InterNetwork)
                    .Select(ip => ip.ToString())
                    .ToList();
            }
            catch
            {
                return new List<string> { "无法获取本地IP" };
            }
        }

        public static string GetMachineName()
        {
            return Environment.MachineName;
        }

        public static string GetOsVersion()
        {
            return $"{Environment.OSVersion} ({(Environment.Is64BitOperatingSystem ? "64位" : "32位")})";
        }

        public static string GetMacAddress()
        {
            try
            {
                var networkInterface = NetworkInterface.GetAllNetworkInterfaces()
                    .FirstOrDefault(nic => nic.OperationalStatus == OperationalStatus.Up &&
                                          nic.NetworkInterfaceType != NetworkInterfaceType.Loopback);

                return networkInterface?.GetPhysicalAddress().ToString() ?? "无法获取MAC地址";
            }
            catch
            {
                return "无法获取MAC地址";
            }
        }

        public static string GetProcessorInfo()
        {
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor"))
                    using (var collection = searcher.Get())
                    {
                        foreach (var item in collection)
                        {
                            return $"{item["Name"]} ({item["NumberOfCores"]}核)";
                        }
                    }
                }
                return Environment.ProcessorCount + " 核处理器";
            }
            catch
            {
                return Environment.ProcessorCount + " 核处理器";
            }
        }

        public static long GetTotalMemory()
        {
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem"))
                    using (var collection = searcher.Get())
                    {
                        foreach (var item in collection)
                        {
                            var totalMemory = Convert.ToInt64(item["TotalPhysicalMemory"]);
                            return totalMemory / (1024 * 1024); // 转换为MB
                        }
                    }
                }
                return 0;
            }
            catch
            {
                return 0;
            }
        }

        public static string GetSystemUpTime()
        {
            try
            {
                using (var uptime = new PerformanceCounter("System", "System Up Time"))
                {
                    uptime.NextValue();
                    var seconds = (int)uptime.NextValue();
                    var ts = TimeSpan.FromSeconds(seconds);
                    return $"{ts.Days}天 {ts.Hours}小时 {ts.Minutes}分钟";
                }
            }
            catch
            {
                return "无法获取运行时间";
            }
        }
    }
}
